import React from "react";
import { Button, Checkbox, Form, Input, message as antdMessage } from "antd";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux/es/hooks/useDispatch";

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

const App: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch()
  const onFinish = async (values: any) => {
    // 发起登录请求
    const resp = await axios.post("/api/login", values);
    // 获取登录结果
    const { data, code, message } = resp.data;
    // 验证结果
    if (code === 200) {
      // 登录成功
      antdMessage.success(message);
      // 同时保存用户数据
      //  用户数据两种方式保存
      //  方式一： redux
      dispatch({ type: 'loginSuccess', payload: data })
      //  方式二： 本地存储
      // localStorage.setItem("token", data.token);
      // localStorage.setItem("avator", data.avator);
      // localStorage.setItem("nickname", data.nickname);
      // localStorage.setItem("role", data.role);

      // 跳转到首页
      navigate("/");
    } else {
      // 登录失败
      antdMessage.error(message);
    }
  };
  return (
    <div
      style={{
        width: 500,
      }}
    >
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 8, span: 16 }}
        >
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
export default App;
